package com.example.huixue.controller;

import com.example.huixue.common.PageResult;
import com.example.huixue.common.Result;
import com.example.huixue.entity.Comment;
import com.example.huixue.service.CommentService;
import com.example.huixue.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class CommentController {
    
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 获取资源评论列表
     */
    @GetMapping({"/resources/{resourceId}/comments", "/api/resources/{resourceId}/comments"})
    public Result<?> getResourceComments(@PathVariable Long resourceId,
                                       @RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "50") int size) {
        try {
            logger.info("获取资源评论请求: resourceId={}, page={}, size={}", resourceId, page, size);
            
            PageResult<Comment> pageResult = commentService.getResourceComments(resourceId, page, size);
            
            Map<String, Object> result = new HashMap<>();
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("page", page);
            result.put("size", size);
            
            return Result.success("获取评论成功", result);
        } catch (Exception e) {
            logger.error("获取资源评论失败", e);
            return Result.error("获取评论失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取资源评论数量
     */
    @GetMapping({"/resources/{resourceId}/comments/count", "/api/resources/{resourceId}/comments/count"})
    public Result<?> getResourceCommentCount(@PathVariable Long resourceId) {
        try {
            logger.info("获取资源评论数量请求: resourceId={}", resourceId);
            long count = commentService.getResourceCommentCount(resourceId);
            return Result.success("获取评论数量成功", count);
        } catch (Exception e) {
            logger.error("获取资源评论数量失败", e);
            return Result.error("获取评论数量失败：" + e.getMessage());
        }
    }
    
    /**
     * 发表评论
     */
    @PostMapping({"/resources/{resourceId}/comments", "/api/resources/{resourceId}/comments"})
    public Result<?> addComment(@PathVariable Long resourceId, 
                               @RequestBody Map<String, Object> commentData,
                               @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            logger.info("发表评论请求: resourceId={}", resourceId);
            
            String content = (String) commentData.get("content");
            Integer rating = commentData.get("rating") != null ? (Integer) commentData.get("rating") : null;
            
            if (content == null || content.trim().isEmpty()) {
                return Result.error("评论内容不能为空");
            }
            
            // 验证并获取用户信息
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未提供有效的认证令牌，请先登录");
            }
            
            String jwtToken = token.substring(7);
            
            if (!jwtUtil.validateToken(jwtToken)) {
                return Result.error("认证令牌已过期或无效，请重新登录");
            }
            
            // 从token获取用户ID
            Integer userIdInt = jwtUtil.getUserIdFromToken(jwtToken);
            if (userIdInt == null) {
                return Result.error("无法获取用户信息，请重新登录");
            }
            
            Long userId = Long.valueOf(userIdInt);
            
            // 调用服务层添加评论
            Comment comment = commentService.addComment(resourceId, userId, content.trim(), rating);
            
            return Result.success("评论发表成功", comment);
        } catch (Exception e) {
            logger.error("发表评论失败", e);
            return Result.error("发表评论失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新评论
     */
    @PutMapping({"/comments/{commentId}", "/api/comments/{commentId}"})
    public Result<?> updateComment(@PathVariable Long commentId, @RequestBody Map<String, String> commentData) {
        try {
            logger.info("更新评论请求: commentId={}", commentId);
            String content = commentData.get("content");
            
            if (content == null || content.trim().isEmpty()) {
                return Result.error("评论内容不能为空");
            }
            
            Comment comment = commentService.updateComment(commentId, content.trim());
            return Result.success("评论更新成功", comment);
        } catch (Exception e) {
            logger.error("更新评论失败", e);
            return Result.error("更新评论失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping({"/comments/{commentId}", "/api/comments/{commentId}"})
    public Result<?> deleteComment(@PathVariable Long commentId) {
        try {
            logger.info("删除评论请求: commentId={}", commentId);
            commentService.deleteComment(commentId);
            return Result.success("评论删除成功");
        } catch (Exception e) {
            logger.error("删除评论失败", e);
            return Result.error("删除评论失败：" + e.getMessage());
        }
    }
    

    
    /**
     * 获取最新评论
     */
    @GetMapping({"/comments/latest", "/api/comments/latest"})
    public Result<?> getLatestComments(@RequestParam(defaultValue = "10") int limit) {
        try {
            logger.info("获取最新评论请求: limit={}", limit);
            return Result.success("获取最新评论成功", commentService.getLatestComments(limit));
        } catch (Exception e) {
            logger.error("获取最新评论失败", e);
            return Result.error("获取最新评论失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员获取所有评论列表（分页）
     */
    @GetMapping("/api/admin/comments")
    public Result<?> getAllComments(@RequestHeader("Authorization") String token,
                                   @RequestParam(defaultValue = "1") int current,
                                   @RequestParam(defaultValue = "10") int size,
                                   @RequestParam(required = false) String keyword) {
        try {
            logger.info("管理员获取评论列表请求: current={}, size={}, keyword={}", current, size, keyword);
            
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "未提供有效的认证令牌");
            }
            
            PageResult<Comment> result = commentService.getAllCommentsWithPagination(current, size, keyword);
            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取评论列表失败", e);
            return Result.error("获取评论列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员批量删除评论
     */
    @DeleteMapping("/api/admin/comments/batch")
    public Result<?> batchDeleteComments(@RequestHeader("Authorization") String token,
                                        @RequestBody Map<String, Object> requestData) {
        try {
            logger.info("管理员批量删除评论请求");
            
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "未提供有效的认证令牌");
            }
            
            @SuppressWarnings("unchecked")
            java.util.List<Object> rawCommentIds = (java.util.List<Object>) requestData.get("commentIds");
            
            if (rawCommentIds == null || rawCommentIds.isEmpty()) {
                return Result.error("评论ID列表不能为空");
            }
            
            // 转换ID类型
            java.util.List<Long> commentIds = rawCommentIds.stream()
                .map(id -> Long.valueOf(id.toString()))
                .collect(java.util.stream.Collectors.toList());
            
            commentService.batchDeleteComments(commentIds);
            logger.info("批量删除评论成功: {}", commentIds);
            return Result.success("批量删除成功");
        } catch (Exception e) {
            logger.error("批量删除评论失败", e);
            return Result.error("批量删除评论失败：" + e.getMessage());
        }
    }
} 